import 'package:flutter/material.dart';
import 'package:jxchmz/API/%E5%BA%93%E5%AD%98%E7%AE%A1%E7%90%86/KuCunManager.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/KSProgressDialog.dart';
import 'package:get/get.dart';
class GoodsSearch extends StatefulWidget {
  @override
  _GoodsSearchState createState() => new _GoodsSearchState();
}

class _GoodsSearchState extends State<GoodsSearch> {
  //输入RFID
  TextEditingController EPCController = new TextEditingController();
  //物资类别数组
   List<PopupMenuItem<String>> GoodsTypeList = [];
  List GoodsTypeListChild = [];
  //物资数组
  List<PopupMenuItem<String>> GoodsList= [];
  List GoodsListChild = [];
  //仓库数组
  List<PopupMenuItem<String>> CangKuList= [];
  List CangKuListChild = [];

  //仓库id
  var warehouseId ;
  var warehouseName;
  //物料id
  var materialId ;
  var materialName;
  //物料类别id
  var jxcMaterialCategoryId ;
  var jxcMaterialCategoryName;

  //物资列表
  var MaterialList = [];
// 当前页数
  int  _page = 1;
  // 是否还有
  bool _hasMore = true;
  // 滚动控制器
  ScrollController _scrollController = new ScrollController();


//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 监听滚动事件
    _scrollController.addListener((){
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixel = _scrollController.position.pixels;
      if (maxScroll == pixel) {
        if(_hasMore){
          _page++;
          Search();
        }

      }
    });
    Future.delayed(Duration.zero,(){
      // //获取物料类别
      GetGoodsType();
      // //获取物料
      GetGoods();
      // //获取仓库
      GetCangKu();
      Search();
    });
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return Scaffold(
      backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text("Inventoryinquiry".tr, style: TextStyle(fontSize: 15, color: Colors.black),),
          centerTitle: true,
          elevation: 0,
          iconTheme: IconThemeData(
            color: Colors.black
          ),
        ),
        body: Container(
          padding: EdgeInsets.all(15),
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: EPCController,
                      decoration: InputDecoration(
                          hintText: "EntertheRFIDnumbertosearch".tr
                      ),
                    ),
                  ),
                  //按钮组
                  MaterialButton(
                    minWidth: 70,
                    height: 30,
                    child: Text("Search".tr,style: TextStyle(color: Colors.white),),
                    onPressed: (){
                      _page = 1;
                      _hasMore = true;
                      MaterialList.clear();
                    Search();
                    },
                    shape: const RoundedRectangleBorder(
                      //边框圆角
                      borderRadius: BorderRadius.all(
                        Radius.circular(5),
                      ),
                    ),
                    color: Colors.blue,
                  ),
                  Container(
                    width: 15,
                  ),
                  MaterialButton(
                    //按钮最小宽度
                    minWidth: 70,
                    height: 30,
                    child: Text("reset".tr,style: TextStyle(color: Colors.blue),),
                    onPressed: (){
                      Clear();
                      //获取库存
                      _page = 1;
                      _hasMore = true;
                      MaterialList.clear();
                      Search();
                    },
                    shape: const RoundedRectangleBorder(
                      //边框颜色
                      side: BorderSide(
                        color: Colors.blue,
                        width: 1,
                      ),
                      //边框圆角
                      borderRadius: BorderRadius.all(
                        Radius.circular(5),
                      ),
                    ),

                    color: Colors.white,
                  ),

                  // TextButton(
                  //   child: Text("重置",style: TextStyle(color: Colors.blue),),
                  //   onPressed: (){
                  //
                  //   },
                  // )
                ],
              ),
              Container(
                height: 15,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  //弹出菜单筛选物资类别
                  PopupMeunGoodsType(),
                  //弹出菜单筛选物资
                  PopupMeunGoods(),
                  //弹出菜单筛选仓库
                  PopupMeunCangKu(),
                ],
              ),
              Container(
                height: 15,
              ),
              //列表
              WidgetGoodsList(),
            ],
          ),
        )
    );
  }
  //弹出菜单筛选物资类别
  Widget PopupMeunGoodsType(){
    return PopupMenuButton<String>(
      onSelected: (value,) {
        print("选择的物资类别数据:$value");
        jxcMaterialCategoryId = value;
        GoodsTypeListChild.forEach((item) {
          if(item['id']==value){
            jxcMaterialCategoryName = item['name'];
          }
        });
        _page = 1;
        _hasMore = true;
        MaterialList.clear();
        Search();
      setState(() {
      });
      },
      child: Row(
        children: [
          Text(jxcMaterialCategoryId==null?'Selectanitemcategory'.tr:jxcMaterialCategoryName),
          Icon(Icons.arrow_drop_down)
        ],
      ),
      itemBuilder: (context) {
        return GoodsTypeList;
      },
    );

  }
  //弹出菜单筛选物资
  Widget PopupMeunGoods(){
    return PopupMenuButton<String>(
      onSelected: (value) {
        print("选择的物资数据:$value");
        materialId = value;
        GoodsListChild.forEach((item) {
          if(item['id']==value){
            materialName = item['name'];
          }
        });
        _page = 1;
        _hasMore = true;
        MaterialList.clear();
        Search();
        setState(() {
        });
      },
      child: Row(
        children: [
          Text(materialId==null?'Selecttheitem'.tr:materialName),
          Icon(Icons.arrow_drop_down)
        ],
      ),
      itemBuilder: (context) {
        return GoodsList;
      },
    );

  }
  //弹出菜单筛选仓库
  Widget PopupMeunCangKu(){
    return PopupMenuButton<String>(
      onSelected: (value) {
        print("选择的仓库数据:$value");
        warehouseId = value;
        CangKuListChild.forEach((item) {
          if(item['id']==value){
            warehouseName = item['name'];
          }
        });
        _page = 1;
        _hasMore = true;
        MaterialList.clear();
        Search();
        setState(() {
        });
      },
      child: Row(
        children: [
          Text(warehouseId==null?'Selecttherepository'.tr:warehouseName),
          Icon(Icons.arrow_drop_down)
        ],
      ),
      itemBuilder: (context) {
        return CangKuList;
      },
    );

  }
  //列表
Widget WidgetGoodsList(){
    return Expanded(
      child: ListView.separated(
        controller: _scrollController,
        itemBuilder: (context,index){
          return ListTile(
            title: Column(
              children: [
                Container(
                  alignment: Alignment.centerLeft,
                  child: Text("RFID:${MaterialList[index]['rfidCode']}",style: TextStyle(fontSize: 13),),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      child: Text("material".tr+":${MaterialList[index]['materialIdName']}",style: TextStyle(fontSize: 13)),
                    ),
                    Container(
                      child: Text("Itemcategory".tr+":${MaterialList[index]['jxcMaterialCategoryIdName']}",style: TextStyle(fontSize: 13)),
                    ),
                  ],
                ),
               Row(
                 mainAxisAlignment: MainAxisAlignment.spaceBetween,
                 children: [
                   Container(
                     child: Text("Thewarehousewhereitislocated".tr+":${MaterialList[index]['warehouseIdName']}",style: TextStyle(fontSize: 13)),
                   ),
                   Container(
                     child: Text("Itemstatus".tr+":${MaterialList[index]['rfidCodeStatus']=="0"?"Entryed".tr:MaterialList[index]['rfidCodeStatus']=="1"?"Outbound".tr:MaterialList[index]['rfidCodeStatus']=="2"?"Returntothewarehouse".tr:MaterialList[index]['rfidCodeStatus']=="3"?"Returnsoutofthewarehouse".tr:"Notinstock".tr}",style: TextStyle(fontSize: 13)),
                   )
                 ],
               ),
                // Container(
                //   alignment: Alignment.centerRight,
                //   child: MaterialButton(
                //     minWidth: 70,
                //     height: 30,
                //     child: Text("查看",style: TextStyle(color: Colors.white),),
                //     onPressed: (){
                //
                //     },
                //     shape: const RoundedRectangleBorder(
                //       //边框圆角
                //       borderRadius: BorderRadius.all(
                //         Radius.circular(5),
                //       ),
                //     ),
                //     color: Colors.green,
                //   ),
                // )
              ],
            ),
          );
        },
        itemCount: MaterialList.length,
        separatorBuilder: (BuildContext context, int index) {
          return Divider();
      },
      ),
    );
}
  //获取物料类别
  GetGoodsType() async {
    var List = [];
    var ResponseData = await KuCunManager().GetGoodsType();
    if(ResponseData['code'] == 200){
      List = ResponseData['data'];
      GoodsTypeListChild =List;
      // 单独提取产品名称
      for (var p = 0; p < List.length; p++) {
        print(List[p]['name'].toString());

        GoodsTypeList.add(
          PopupMenuItem(
            child: SizedBox(
              width: MediaQuery.of(context).size.width-100,
              child: Text(List[p]['name']),
            ),
            value: List[p]['id'],
          )
        );
      }
    }else {
      new GetxTools().ErrorToast("Failedtoobtainmaterialcategoryinformation".tr);
    }
    setState(() {});
  }
  //获取物料
  GetGoods() async {
    var List = [];
    var ResponseData = await KuCunManager().GetGoods();
    if(ResponseData['code'] == 200){
      List = ResponseData['rows'];
      GoodsListChild = List;
      // 单独提取产品名称
      for (var p = 0; p < List.length; p++) {
        GoodsList.add(PopupMenuItem(
          child: SizedBox(
            width: MediaQuery.of(context).size.width-100,
            child: Text(List[p]['name']),
          ),
          value: List[p]['id'],
        ));
      }
    }else {
      new GetxTools().ErrorToast("Failedtoobtainmaterialinformation".tr);
    }
    setState(() {});
  }
  //获取仓库
  GetCangKu() async {
    var List = [];
    var ResponseData = await KuCunManager().GetCangKu();
    if(ResponseData['code'] == 200){
      List = ResponseData['rows'];
      CangKuListChild = List;
      // 单独提取产品名称
      for (var p = 0; p < List.length; p++) {
        CangKuList.add(PopupMenuItem(
          child:SizedBox(
            width: MediaQuery.of(context).size.width-100,
            child: Text(List[p]['name']),
          ),
          value: List[p]['id'],
        ));
      }
    }else {
      new GetxTools().ErrorToast("Failedtogetrepositoryinformation".tr);
    }
    setState(() {});
  }


  //搜索事件
Search() async {
  //搜索参数
  var data = {
    "pageNum": _page,
    "pageSize": 10,
    "warehouseId": warehouseId,
    "materialId": materialId,
    "rfidCode": EPCController.text,
    "rfidCodeStatus": null,
    "reasonable" :false,
    "jxcMaterialCategoryId":jxcMaterialCategoryId
  };
  KSProgressDialog().LoadingToast("Searching".tr, context);
  var ResponseData = await KuCunManager().SearchKuCun(data);
  KSProgressDialog().CloseLoading();
  if(ResponseData['code'] == 200){
    print("搜搜结果");
    var List = [];
    List= ResponseData['rows'];
    if(List.length<=0){
      // 关闭加载
      this._hasMore = false;

    }else{
      List.forEach((element) {
        MaterialList.add(element);
      });
    }
  }else {

  }
  setState(() {});
}
Clear(){
  jxcMaterialCategoryId = null;
  jxcMaterialCategoryName = null;
  materialId = null;
  materialName = null;
  warehouseName = null;
  warehouseId = null;
  EPCController.clear();
  setState(() {
  });
}
}
